﻿
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.InteropServices;

namespace Test_2D
{
    public partial class EditForm : WeifenLuo.WinFormsUI.Docking.DockContent
    {
        public EditForm()
        {
            InitializeComponent();

            animation = new Animation();        /////////////////////////////
            comList = new List<Component>();
            canvas = new Canvas(new Size(400, 300), Color.White);
            frameData = new FrameData(0, 0);

            animation.TimeLines.Add(new TimeLine());    //创建0号时间轴
            //timeline = animation.TimeLines[0];      //默认当前时间轴为0号时间轴
        }

        public EditForm(SourceFile _sourceFile)
        {
            InitializeComponent();
            //this.sourceFile = _sourceFile;

            animation = _sourceFile.Animation;
            comList = _sourceFile.ComList;
            canvas = _sourceFile.Canvas;
            frameData = _sourceFile.FrameData;

            //timeline = animation.TimeLines[0];
        }

        private void EditForm_Load(object sender, EventArgs e)
        {

            //this.Canvas = new Canvas(400, 300, Color.White);

            pickBox = new PickBox(panel2);      //向画布添加图片控制类
            pickBox.PicBoxRightClick += new PicBox_RightClick(pickBox_PicBoxRightClick);
            /*
            if (this.sourceFile != null)
            {
                this.animation = sourceFile.Animation;
                this.comList = sourceFile.ComList;
                this.Canvas = sourceFile.Canvas;

                timeline = animation.TimeLines[0];
            }
            else
            {
                       //设置画布初始值
            }*/
        }

        void pickBox_PicBoxRightClick(object sender, MouseEventArgs e)
        {
            contextMenuStrip1.Show((PictureBox)sender, e.Location);
            //throw new NotImplementedException();
        }

        [DllImportAttribute("user32.dll")] //winuser.h
        private static extern Boolean ShowWindow(IntPtr hWnd, Int32 nCmdShow);

        //[DllImport("User32.dll", CharSet = CharSet.Auto)]
        //public static extern int ShowWindow(IntPtr hWnd, short cmdShow);

        public SourceFile SourceFile
        {
            get { return new SourceFile(comList, animation, canvas, frameData); }
        }

        List<Component> comList;//!!!
        public List<Component> ComList
        {
            get { return comList; }
        }

        Animation animation;//!!!
        public Animation Animation
        {
            get { return animation; }
        }

        Canvas canvas;
        public Canvas Canvas
        {
            get { return canvas; }
                //Image img = panel2.BackgroundImage;
                //return new Canvas(panel2.Size, img.Size, new Bitmap(panel2.BackgroundImage).GetPixel(0, 0));
            set 
            {
                canvas = value;
                Canvas_Change(canvas); 
            }
        }

        /// <summary>
        /// 设定控制此类的时间轴
        /// </summary>
        FrameForm frameForm;
        public FrameForm FrameForm
        {
            set { this.frameForm = value; }
        }

        FrameData frameData;
        public FrameData FrameData
        {
            get { return frameData; }
        }

        string filePath = "", fileName = "";
        public string FilePath
        {
            get { return filePath; }
            set { this.filePath = value; }
        }
        public string FileName
        {
            get 
            {
                if (filePath == "")
                    return fileName;    //文件没保存就显示默认文件名
                else
                    return System.IO.Path.GetFileNameWithoutExtension(filePath); 
            }
            set { this.fileName = value; }  //设置默认文件名
        }

        PickBox pickBox;

        List<PictureBox> picboxs = new List<PictureBox>();      //当前帧的所有运动元构成的picbox列表,用来显示在画布上

        TimeLine timeLine
        {
            get { return animation.TimeLines[frameData.TimeLineIndex]; }   
        }
        Frame frame
        {
            get { return timeLine.Frames[frameData.FrameIndex]; }
        }



        //画布 ，添加Pictruebox
        private void canvas_DragEnter(object sender, DragEventArgs e)
        {
            if (frameForm.IsKeyFrame)
            {
                if (e.Data.GetDataPresent(typeof(Component)))
                    e.Effect = DragDropEffects.Copy;
                else
                    e.Effect = DragDropEffects.None;
            }
        }

        private void canvas_DragDrop(object sender, DragEventArgs e)
        {
            //此帧是关键帧才可以拖进运动元
            if (frameForm.IsKeyFrame)
            {
                Component tmp_com = (Component)e.Data.GetData(typeof(Component));   //获得元件
                Point pot = panel2.PointToClient(new Point(e.X, e.Y));              //获得鼠标释放的坐标
                Motion tmp_mot = new Motion(tmp_com, 1, pot);       //新建运动元
                frame.Motions.Add(tmp_mot);    //向当前帧添加运动元
                newPicbox(tmp_mot);            //添加代表运动元的picBox
            }
            this.Activate();
        }


        //刷新为指定帧的运动元,但不一定是当前帧的!!!!!!  int timeline_index, int frame_index考虑删除
        /// <summary>
        /// 切换帧事件, 刷新当前帧，但调用此方法时要保证当前帧为关键帧
        /// </summary>
        /// <param name="timeline_index"></param>
        /// <param name="frame_index"></param>
        public void frame_Change(int timeline_index, int frame_index)
        {
            //TimeLine tmp_timeLine = animation.TimeLines[timeline_index];
            //timeline = animation.TimeLines[timeline_index];
            pickBox.Remove();   //隐藏控制点
            foreach (PictureBox picBox in picboxs)
                picBox.Dispose();

            if (frame_index != -1)  //-1表示清空画布
            {
                foreach (TimeLine tmp_timeLine in animation.TimeLines)
                {
                    if (tmp_timeLine.Visible == false)
                        continue;
                    else
                    {
                        foreach (Motion mot in tmp_timeLine.Frames[frameData.FrameIndex].Motions)//timeLine.Frames[frame_index].Motions)//
                            newPicbox(mot);
                    }
                }
            }
        }

        private void newPicbox(Motion _mot)
        {
            PictureBox newpicbox = new PictureBox();
            newpicbox.BackColor = Color.White;
            newpicbox.BackgroundImageLayout = ImageLayout.Stretch;
            //newpicbox.BorderStyle = BorderStyle.FixedSingle;

            newpicbox.Size = _mot.Size;
            newpicbox.BackgroundImage = _mot.Image;
            newpicbox.Tag = _mot;
            newpicbox.Location = _mot.Location;

            //newpicbox.MouseMove += new System.Windows.Forms.MouseEventHandler(this.pictureBox_MouseMove);
            //newpicbox.MouseDown += new System.Windows.Forms.MouseEventHandler(this.pictureBox_MouseDown);
            //newpicbox.MouseUp += new System.Windows.Forms.MouseEventHandler(this.pictureBox_MouseUp);


            this.panel2.Controls.Add(newpicbox);
            pickBox.WireControl(newpicbox);
            picboxs.Add(newpicbox);
            //newpicbox.BringToFront();


            //cur_picbox = newpicbox;
        }

        //设置画布大小
        private void Canvas_Change(Canvas cvs)
        {
            Bitmap bp = new Bitmap(cvs.Size.Width, cvs.Size.Height);
            Graphics g = Graphics.FromImage(bp);
            g.Clear(cvs.Color);
            panel2.Size = cvs.BackgroundSize;
            panel2.BackgroundImage = bp;

            this.AutoScrollPosition = new Point((HorizontalScroll.Maximum - ClientSize.Width) / 2,
                (VerticalScroll.Maximum - ClientSize.Height) / 2);  //滚动条居中

            //label1.Text = this.HorizontalScroll.Maximum + "|" + this.ClientSize.Width;
            //this.HorizontalScroll.Value = (HorizontalScroll.Maximum - ClientSize.Width) / 2;
            //this.VerticalScroll.Value = (VerticalScroll.Maximum - ClientSize.Height) / 2;
            //VerticalScroll.Value = VerticalScroll.Maximum / 2;
            //画布居中
            //MessageBox.Show(this.HorizontalScroll.Maximum.ToString());

            //this.AutoScrollPosition = new Point(this.HorizontalScroll.Maximum / 2 - this.HorizontalScroll.LargeChange / 2,
            //    this.VerticalScroll.Maximum / 2 - this.VerticalScroll.LargeChange / 2);
            // panel1.AutoScrollPosition = new Point(panel1.HorizontalScroll.Maximum / 2 - panel1.HorizontalScroll.LargeChange / 2,
            //    panel1.VerticalScroll.Maximum / 2 - panel1.VerticalScroll.LargeChange / 2);
        }

        //窗体键盘事件处理，主要用来处理picbox的位置
        private void EditForm_KeyDown(object sender, KeyEventArgs e)
        {
            /*
            MessageBox.Show("keyDown");
            if (cur_picbox != null)
            {
                switch (e.KeyCode)
                {
                    case Keys.Left: cur_picbox.Left -= 1; newLocation(); break;
                    case Keys.Up: cur_picbox.Top -= 1; newLocation(); break;
                    case Keys.Right: cur_picbox.Left += 1; newLocation(); break;
                    case Keys.Down: cur_picbox.Top += 1; newLocation(); break;
                }
            }*/
        }

        private void newLocation()
        {
            //((Motion)pic Tag).Location = cur_picbox.Location;            //新坐标
        }

        private void panel2_Click(object sender, EventArgs e)
        {
            this.Activate();
        }

        /// <summary>
        /// editForm比较特殊,需要在show(dockPanel)后在设置Canvas,否则滚动条无法居中。
        /// </summary>
        /// <param name="dockPanel"></param>
        /// <param name="flag"> flag没用，只是用来标记要执行此函数</param>
        public void Show(WeifenLuo.WinFormsUI.Docking.DockPanel dockPanel, bool flag)
        {
            Show(dockPanel);
            Canvas_Change(canvas);
        }

        private void 删除ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //MessageBox.Show(pickBox.SelectPicBox.Tag.ToString());
            pickBox.Remove();       //隐藏图片控制点

            pickBox.SelectPicBox.Dispose();         //从画布上删除  
            frame.Motions.Remove((Motion)pickBox.SelectPicBox.Tag);     //从Motions中删除
        }
/*
//菜单栏菜单事件
        private void 新建ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            animation = new Animation();        /////////////////////////////
            comList = new List<Component>();

            animation.TimeLines.Add(new Timeline());    //创建0号时间轴
            timeline = animation.TimeLines[0];      //默认当前时间轴为0号时间轴
        }

        private void 打开ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                FileStream fs = new FileStream(openFileDialog1.FileName, FileMode.Open);
                BinaryFormatter formatter = new BinaryFormatter();
                SourceFile sourceFile = (SourceFile)formatter.Deserialize(fs);

                animation = sourceFile.Animation;
                comList = sourceFile.ComList;
                this.Canvas = sourceFile.Canvas;
                fs.Close();

                foreach (Component com in comList)
                {
                    listView_Add(com);
                }
                timeline = animation.TimeLines[0];
                
            }
        }

        private void 保存ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //FileStream fs = new FileStream(@"..\..\Test.dat", FileMode.Create);
            BinaryFormatter bf = new BinaryFormatter();
            //bf.Serialize(fs, animation);
            //fs.Close();
        }

        private void 另存为ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                FileStream fs = new FileStream(saveFileDialog1.FileName, FileMode.Create);
                BinaryFormatter formatter = new BinaryFormatter();
                formatter.Serialize(fs, new SourceFile(comList, animation, this.Canvas));
                fs.Close();
            }
        }

        private void 导入元件ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AddCom addcom = new AddCom();
            addcom.ShowDialog();
            if (addcom.newcom == true)
            {
                comList.Add(addcom.Component);      //添加到元件列表中
                listView_Add(addcom.Component);
            }
            addcom.Dispose();
        }

        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }*/

//菜单编辑事件
        //画布设置

    }
}
